<template>
  <div class="app-container">
    <el-form :model="searchForm" label-width="80px" @keyup.enter.native="search()">
      <el-row>
        <el-col class="other">
          <el-form-item label="姓名" size="small">
            <el-input v-model="searchForm.insuredName"></el-input>
          </el-form-item>
        </el-col>
        <!--        <el-col class="other">-->
        <!--          <el-form-item label="所属团队" size="small">-->
        <!--            <el-input v-model="searchForm.teamName"></el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->
        <el-col class="other">
          <el-form-item label="职称" size="small">
            <el-select v-model="searchForm.jobTitle" placeholder="请选择">
              <el-option value="" label="全部"></el-option>
              <el-option
                v-for="item in global.jobTitleList"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="职称专业" size="small">
            <el-input v-model="searchForm.jobTitleProfession"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="other">
          <el-form-item label="执业注册" size="small">
            <el-input v-model="searchForm.professionalRegistered"></el-input>
          </el-form-item>
        </el-col>
        <el-col class="searchBtn">
          <el-form-item size="small">
            <el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <my-table
      :data="tableData"
      :col-configs="colConfigs"
      v-loading="listLoading"
      :page-num="pageNum"
      :page-size="pageSize"
      @fetchData="fetchData"
      @openVisible="openVisible"
    >
      <el-table-column
        slot="opt"
        fixed="right"
        label="操作"
        width="80"
        v-if="roleType===0 || roleType===1 || roleType===5 || roleType===9"
      >
        <template slot-scope="scope">
          <el-button
            @click.native.prevent="editTeam(scope.row.collectId)"
            type="text"
            size="small">
            修改
          </el-button>
        </template>
      </el-table-column>
    </my-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :title="dialogTitle" :visible.sync="outerVisible" width="650px">
      <el-form ref="teamRow" :rules="rules" :model="teamRow" label-width="100px">
        <el-row>
          <el-col class="dialog-line">
            <el-form-item label="姓名" size="small">
              {{teamRow.employeeName}}
            </el-form-item>
          </el-col>
          <el-col class="dialog-line">
            <el-form-item label="所属团队" size="small">
              {{teamRow.teamName}}
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-form-item label="获奖" size="small">-->
        <!--          <el-input type="text" v-model="teamRow.award"></el-input>-->
        <!--        </el-form-item>-->
        <el-row>
          <el-col>
            <el-form-item label="业绩" size="small">
              <el-input type="textarea" v-model="teamRow.performance" :rows="3"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" size="small" @click="submitForm('teamRow')" v-no-more-click>确定</el-button>
        <el-button size="small" @click="outerVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="imgMsg.label" :visible.sync="imgVisible" width="600px">
      <img class="img-dialog" :src="`${global.exportUrl}${imgMsg.src}`" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import { getList, selectCollect, updateCollect } from '@/api/bidemployee1'
  import myTable from '@/components/myTable'
  import global from '@/components/global'

  import { AreaSelect } from 'vue-area-linkage'
  import { pca } from 'area-data'
  import { formatDate } from '@/utils/index'

  const filePath = {
    props: ['colConfig'],
    data() {
      return {
        collectId: '',
        prop: '',
        precent: 0,
        progress: ''
      }
    },
    methods: {
      openVisible(label, src) {
        const msg = {
          label: label,
          src: src
        }
        this.$emit('openImgVisible', msg)
      },
      downloadFile(row, prop, column) {
        this.row = row
        this.column = column
        this.collectId = row.collectId
        this.prop = prop
        this.$refs.file.click()
      },
      upLoad(upLoad, params, callback1, callback2) {
        upLoad(params, function(progressEvent) { // 原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            // 属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
            // 如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
            callback1(progressEvent)
          }
        }).then(res => {
          callback2(res.data)
        }).catch(() => {
          this.$refs.file.value = ''
          this.progress = ''
        })
      },
      fileChanged() {
        const _this = this
        _this.progress = `${_this.row.collectId}${_this.column.id}`
        _this.precent = 0
        const params = new FormData()
        params.append('collectId', this.collectId)
        params.append(`${this.prop}File`, this.$refs.file.files[0])
        _this.upLoad(updateCollect, params, (res) => {
          const loaded = res.loaded
          const total = res.total
          _this.$nextTick(() => {
            _this.precent = (loaded / total) * 100
          })
        }, (res) => {
          _this.$refs.file.value = ''
          _this.progress = ''
          _this.$emit('fetchData')
        })
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :min-width="colConfig.minWidth">
  <input class="file" type="file" @change="fileChanged" ref="file"/>
      <span slot-scope="scope">
        <div v-if="colConfig.type==='img'">
          <a v-if="scope.row[colConfig.prop]" @click="openVisible(colConfig.label,scope.row[colConfig.prop])">查看
          </a>
          <a v-else style="color: red">X</a>
        </div>
        <div v-else-if="colConfig.type==='filePath'">
            <div v-if="scope.row[colConfig.prop]">
              <a @click="downloadFile(scope.row,colConfig.prop,scope.column)">上传</a>
              <a target="_blank" :href="GLOBAL.filePathUrl+encodeURI(scope.row[colConfig.prop])">下载</a>
              <el-progress :text-inside="true" :stroke-width="15" v-if="progress===(scope.row.collectId+scope.column.id)" :percentage="precent" status="success"></el-progress>
            </div>
            <div v-else>
              <a style="color: red" >X</a>
              <a @click="downloadFile(scope.row,colConfig.prop,scope.column)">上传</a>
              <el-progress :text-inside="true" :stroke-width="15" v-if="progress===(scope.row.collectId+scope.column.id)" :percentage="precent" status="success"></el-progress>
            </div>
        </div>
        <div v-else>
          <a v-if="scope.row[colConfig.prop]" target="_blank" :href="GLOBAL.filePathUrl+encodeURI(scope.row[colConfig.prop])">下载</a>
        </div>
      </span>
  </el-table-column>
  `
  }

  const startTime = {
    props: ['colConfig'],
    filters: {
      formatDate(time) {
        if (time) {
          var date = new Date(time)
          return formatDate(date, 'yyyy-MM-dd')
        }
      }
    },
    template: `
  <el-table-column :label="colConfig.label" :width="colConfig.width">
      <span slot-scope="scope">
        {{ scope.row[colConfig.prop] | formatDate }}
      </span>
  </el-table-column>
  `
  }

  const formatter = function(row, column) {
    if (row[column.property]) {
      let obj = {}
      obj = global[`${column.property}ListBranch`].find((item) => {
        return item.value === parseInt(row[column.property]) // 筛选出匹配数据
      })
      return obj.label
    }
  }

  const configs = {
    props: ['colConfig'],
    filters: {
      formatMonth(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyyMM')
      },
      formatDate(time) {
        var date = new Date(time)
        return formatDate(date, 'yyyyMMdd')
      },
      formatTime(time) {
        console.log(time)
        var date = new Date(time)
        return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
      },
      formatter(row, prop) {
        if (row[prop]) {
          let obj = {}
          obj = global[`${prop}ListBranch`].find((item) => {
            return item.value === row[prop] // 筛选出匹配数据
          })
          return obj.label
        }
      }
    },
    template: `
  <el-table-column :label="colConfig.label">
            <el-table-column  v-for="(item, index) in colConfig.children"  :label="item.label" :width="item.width">
                <span slot-scope="scope" >
                    <span v-if="item.component==='month'"> {{ scope.row[item.prop] | formatMonth }}</span>
                    <span v-else-if="item.component==='time'"> {{ scope.row[item.prop] | formatDate }}</span>
                    <span v-else-if="item.component==='formatter'"> {{ scope.row,item.prop | formatter }}</span>
                    <span v-else >{{scope.row[item.prop]}}</span>
                </span>
            </el-table-column>
  </el-table-column>
  `
  }

  const ward = function(row, column) {
    let ward = ''
    row.ward.forEach(value => {
      ward += `${value.remark},`
    })
    return ward.slice(0, -1)
  }

  export default {
    components: {
      myTable,
      AreaSelect
    },
    data() {
      return {
        colConfigs: [
          { prop: 'name', label: '姓名', width: '100', fixed: true },
          { prop: 'teamName', label: '所属团队', width: '100', fixed: true },
          {
            label: '职称', children: [
              { prop: 'jobTitle', label: '职称', width: '100', component: 'formatter' },
              { prop: 'jobTitleProfession', label: '专业', width: '150' }
            ], component: configs
          },
          {
            label: '执业注册', children: [
              { prop: 'professionalRegistered', label: '注册', width: '150' }
            ], component: configs
          },
          { prop: 'idNumber', label: '身份证', width: '100', type: 'img', component: filePath },
          { prop: 'diploma', label: '毕业证', width: '100', type: 'img', component: filePath },
          { prop: 'technicalPosition', label: '职称证', width: '100', type: 'img', component: filePath },
          { prop: 'registration', label: '注册证', width: '100', type: 'img', component: filePath },
          { prop: 'insuredStatus', label: '参保状态', width: '100', formatter: formatter },
          { prop: 'socialSecurityTime', label: '初始参保时间', width: '100', component: startTime },
          { prop: 'ward', label: '获奖', width: '100', formatter: ward },
          { prop: 'performance', label: '业绩', width: '150' },
          // { prop: 'insuredUnit', label: '参保单位', width: '100', formatter: formatter }
          { slot: 'opt' }
        ],
        searchForm: {},
        searchFormList: {},
        tenderNames: [],
        infoTitles: [],
        listLoading: true,
        dialogTitle: '新增人员',
        dialogType: 0,
        teamRow: {},
        teamRowClear: {},
        tableData: [],
        pageNum: 1,
        pageSize: 10,
        total: 1,
        outerVisible: false,
        innerVisible: false,
        pca: pca,
        rules: {},
        visible: false,
        imgVisible: false,
        imgMsg: {}
      }
    },
    created() {
      this.teamRowClear = JSON.parse(JSON.stringify(this.teamRow))
      this.fetchData()
    },
    computed: {
      global() {
        return global
      },
      roleType() {
        return this.$store.state.user.roleType
      }
    },
    methods: {
      fetchData() {
        this.searchFormList.pageNum = this.pageNum
        this.searchFormList.pageSize = this.pageSize
        this.listLoading = true
        console.log(this.searchFormList)
        getList(this.searchFormList).then(response => {
          this.tableData = response.responseBody.list
          this.total = response.responseBody.total
          this.listLoading = false
        })
      },
      search() {
        this.pageNum = 1
        this.searchFormList = JSON.parse(JSON.stringify(this.searchForm))
        this.fetchData()
      },
      fileClear() {
        if (this.$refs.awardFile) {
          this.$refs.awardFile.value = ''
        }
      },
      addTeam() {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '新增人员'
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.teamRow.isTender = 1
        this.dialogType = 1
        this.fileClear()
      },
      editTeam(collectId) {
        if (this.$refs['teamRow']) {
          this.$refs['teamRow'].resetFields()
        }
        this.outerVisible = true
        this.dialogTitle = '修改人员'
        this.dialogType = 0
        this.teamRow = JSON.parse(JSON.stringify(this.teamRowClear))
        this.fileClear()
        const params = {
          collectId: collectId
        }
        selectCollect(params).then(response => {
          const data = response.responseBody
          this.teamRow = Object.assign({}, this.teamRow, data)
        })
      },
      submitForm(formName) {
        const params = new FormData()
        params.append('performance', this.teamRow.performance)
        if (!this.dialogType) {
          params.append('collectId', this.teamRow.collectId)
        }
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.dialogType) {
              addOperation(params).then(response => {
                console.log(response)
                this.outerVisible = false
                this.fetchData()
              })
            } else {
              updateCollect(params).then(response => {
                this.outerVisible = false
                this.fetchData()
              })
            }
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      deleteRow(scope) {
        this.$refs[`popover-${scope.$index}`].doClose()
        const params = new FormData()
        params.append('operationId', scope.row.operationId)
        params.append('isDel', 1)
        deleteOperation(params).then(response => {
          this.fetchData()
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.pageNum = val
        this.fetchData()
      },
      fileUpload(event, teamRowName) {
        this.$set(this.teamRow, teamRowName, event.target.files[0])
      },
      openVisible(msg) {
        this.imgVisible = true
        this.imgMsg = msg
      }
    },
    mounted() {
      console.log(this.pca)
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  .app-container {
    .el-pagination {
      margin-top: 20px;
    }

    .table-btn {
      margin-bottom: 10px;

      & > button {
        margin: 0 20px;
      }

      .el-dialog {
        textarea {
          margin-top: 10px;
        }

        .el-checkbox {
          margin-right: 20px;
        }

        .el-checkbox + .el-checkbox {
          margin-left: 0;
        }
      }
    }

    .item-inline {
      display: inline-block;
      width: 400px;
    }

    .img-dialog {
      max-width: 540px;
    }
  }

</style>


<style rel="stylesheet/scss" lang="scss">
  .el-input__icon {
    line-height: 100%;
  }

  .el-form-item__content {
    line-height: 33px;
  }

  .area-select .area-selected-trigger {
    padding: 0 10px;
  }

  a, a:focus, a:hover {
    color: #409EFF;
  }

  /*.el-table__body tr.hover-row>td {
    background-color: #0000ff !important;
  }

  .el-table__body tr.current-row>td {
    background-color: #0000ff !important;
  }*/
</style>
